package com.dingwen.treasure.manage.service;

import com.dingwen.treasure.base.constant.RedisConstant;
import com.dingwen.treasure.base.exception.AuthException;
import com.dingwen.treasure.model.entity.mybatisplus.SysUser;
import com.dingwen.treasure.model.vo.LoginVo;
import com.dingwen.treasure.security.dto.LoginUser;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.*;

/**
 * 　LoginService : 登入 service
 * 　@author dingwen
 * 　@date 2022/6/12
 */
public interface LoginService {

    /**
     * 登录
     *
     * @param username 用户名
     * @param password 暗语
     * @return {@link LoginUser}
     */
    LoginUser doLogin(String username, String password);


    /**
     * 生成登录vo
     *
     * @param sysUser sys用户
     * @param token   代币
     * @return {@link LoginVo}
     */
    LoginVo buildLoginVo(SysUser sysUser, String token);


    /**
     * 判断用户是否被锁定
     *
     * @param account 账户
     * @return boolean
     */
    void lock(String account);

    /**
     * 登录限制
     *
     * @param account 账户
     */
    void limit(String account);


    /**
     * 获取登录密钥
     *
     * @param account 账户
     * @return {@link String}
     */
    default String getKey(String account) {
        return RedisConstant.ACCOUNT_LOCK.concat(account);
    }


    /**
     * 自定义异常信息 </br>
     * <p>待优化点：可以结合国际化完成</p>
     *
     * @param e e 异常信息
     */
    default void customExceptionInfo(Exception e) {
        if (e instanceof LockedException) {
            throw new AuthException(HttpStatus.LOCKED.value(), "账户已被锁定");
        } else if (e instanceof CredentialsExpiredException) {
            throw new AuthException(HttpStatus.UNAUTHORIZED.value(), "密码已过期");
        } else if (e instanceof AccountExpiredException) {
            throw new AuthException(HttpStatus.UNAUTHORIZED.value(), "账户已过期");
        } else if (e instanceof DisabledException) {
            throw new AuthException(HttpStatus.UNAUTHORIZED.value(), "账户已禁用");
        } else if (e instanceof BadCredentialsException) {
            throw new AuthException(HttpStatus.UNAUTHORIZED.value(), "密码错误");
        } else {
            throw new AuthException(HttpStatus.UNAUTHORIZED.value(), e.getMessage());
        }
    }

}
